1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/*!
`isotope` values
*/
use crate::error::*;
use crate::eval::*;
use crate::*;
use fxhash::FxHashMap as HashMap;
use lazy_static::lazy_static;
use num::BigUint;
use smallvec::SmallVec;
use std::cmp::Ordering;
use std::collections::hash_map::Entry;
use std::fmt::{self, Debug, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::*;

mod expr;
mod lambda;
mod lifetime;
mod pi;
mod primitive;
mod reference;
mod symbol;
mod universe;
mod value_enum;
mod value_trait;
mod variance;
pub use expr::*;
pub use lambda::*;
pub use lifetime::*;
pub use pi::*;
pub use primitive::*;
pub use reference::*;
pub use symbol::*;
pub use universe::*;
pub use value_enum::*;
pub use value_trait::*;
pub use variance::*;

/// A `rain` value
#[derive(Clone, Eq, PartialEq)]
#[repr(transparent)]
pub struct ValId(pub Arc<ValueEnum>);

impl ValId {
    /// Directly produce a new `ValId` from a `ValueEnum`
    #[inline]
    pub fn new_direct(value: ValueEnum) -> ValId {
        ValId(Arc::new(value))
    }
    /// Get this `ValId` as a pointer
    #[inline]
    pub fn as_ptr(&self) -> *const ValueEnum {
        Arc::as_ptr(&self.0)
    }
    /// Check whether this `ValId` is pointer-equal to another
    #[inline]
    pub fn ptr_eq(&self, other: &ValId) -> bool {
        self.as_ptr() == other.as_ptr()
    }
    /// Get this `ValId` as a `ValueEnum`
    #[inline]
    pub fn as_enum(&self) -> &ValueEnum {
        &self.0
    }
    /// Normalize this `ValId`, returning if any change occured
    #[inline]
    pub fn normalize(&mut self) -> bool {
        if let Some(normal) = self.normalized() {
            *self = normal.clone();
            true
        } else {
            false
        }
    }
    /// Get this `ValId`, but normalized
    #[inline]
    pub fn get_normalized(&self) -> &ValId {
        self.normalized().unwrap_or(self)
    }
    /// Convert an `&ValId` to an `&Option<ValId>`
    #[inline]
    pub fn to_opt(&self) -> &Option<ValId> {
        debug_assert_eq!(
            std::mem::size_of::<ValId>(),
            std::mem::size_of::<Option<ValId>>()
        );
        debug_assert_eq!(
            std::mem::align_of::<ValId>(),
            std::mem::align_of::<Option<ValId>>()
        );
        unsafe { &*(self as *const _ as *const Option<ValId>) }
    }
}

#[allow(clippy::derive_hash_xor_eq)]
impl Hash for ValId {
    #[inline]
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.code().hash(hasher)
    }
}

impl Debug for ValId {
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        Debug::fmt(&self.0, fmt)
    }
}

impl Deref for ValId {
    type Target = ValueEnum;
    #[inline]
    fn deref(&self) -> &ValueEnum {
        &self.0
    }
}

impl Value for ValId {
    #[inline]
    fn is_ty(&self) -> bool {
        self.0.is_ty()
    }
    #[inline]
    fn is_kind(&self) -> bool {
        self.0.is_kind()
    }
    #[inline]
    fn is_groupoid(&self) -> bool {
        self.0.is_groupoid()
    }
    #[inline]
    fn is_instant(&self) -> bool {
        self.0.is_instant()
    }
    #[inline]
    fn elem_constraints(&self) -> Result<&Constraints, Error> {
        self.0.elem_constraints()
    }
    #[inline]
    fn elem_linearity(&self) -> Result<Linearity, Error> {
        self.0.elem_linearity()
    }
    #[inline]
    fn is_lifetime(&self) -> bool {
        self.0.is_lifetime()
    }
    #[inline]
    fn linearity(&self) -> Linearity {
        self.0.linearity()
    }
    #[inline]
    fn is_nonlinear(&self) -> bool {
        self.0.is_nonlinear()
    }
    #[inline]
    fn is_const(&self) -> bool {
        self.0.is_const()
    }
    #[inline]
    fn local_constraints(&self) -> &Constraints {
        self.0.local_constraints()
    }
    #[inline]
    fn instant_constraint(&self) -> Result<&Constraint, Error> {
        self.0.instant_constraint()
    }
    #[inline]
    fn ty(&self) -> &ValId {
        self.0.ty()
    }
    #[inline]
    fn into_enum(self) -> ValueEnum {
        self.as_enum().clone()
    }
    #[inline]
    fn into_valid(self) -> ValId {
        self
    }
    #[inline]
    fn fv(&self) -> &SymbolSet {
        self.0.fv()
    }
    #[inline]
    fn def_fv(&self) -> &SymbolSet {
        self.0.def_fv()
    }
    #[inline]
    fn contains(&self, value: &ValId) -> Result<Match, Error> {
        self.0.contains(value)
    }
    #[inline]
    fn subtype(&self, other: &ValId, variance: Variance) -> Result<Match, Error> {
        self.0.subtype(other, variance)
    }
    #[inline]
    fn try_apply_in_ctx(&self, arg: &ValId, ctx: &mut EvalCtx) -> Result<Application, Error> {
        self.0.try_apply_in_ctx(arg, ctx)
    }
    #[inline]
    fn apply_ty_in_ctx(&self, arg: &ValId, ctx: &mut EvalCtx) -> Result<Abstract, Error> {
        self.0.apply_ty_in_ctx(arg, ctx)
    }
    #[inline]
    fn apply_ty(&self, arg: &ValId) -> Result<Abstract, Error> {
        self.apply_ty_in_ctx(arg, &mut EvalCtx::default())
    }
    #[inline]
    fn eval_in_ctx(&self, ctx: &mut EvalCtx) -> Option<ValId> {
        if ctx.is_not_subst(self.fv()) {
            return None;
        }
        if let Some(cached) = ctx.cached_eval(self) {
            return Some(cached.clone());
        }
        let evaluated = self.0.eval_in_ctx(ctx);
        if let Some(eval) = &evaluated {
            ctx.cache_eval(self.clone(), eval.clone())
        }
        evaluated
    }
    #[inline]
    fn is_normal(&self) -> bool {
        self.0.is_normal()
    }
    #[inline]
    fn normalized(&self) -> Option<&ValId> {
        self.0.normalized()
    }
    #[inline]
    fn code(&self) -> u64 {
        self.0.code()
    }
    #[inline]
    fn normal_code(&self) -> u64 {
        self.0.normal_code()
    }
}

/// Utilities for testing `Value` implementations and similar
pub mod test {
    use super::*;

    /// Perform basic consistency checks on the `Value` trait implementation for an object.
    pub fn basic_value_consistency<V: Debug + Value>(value: V) {
        // Basic construction
        let into_valid = value.clone().into_valid();
        let into_enum = value.clone().into_enum();
        assert_eq!(into_enum, *into_valid.as_enum());

        // Type consistency
        let ty = value.ty();
        assert_eq!(ty, into_valid.ty());
        assert_eq!(ty, into_enum.ty());

        // Linearity consistency
        let ty_lin = value.elem_linearity().ok();
        assert_eq!(ty_lin, into_valid.elem_linearity().ok());
        assert_eq!(ty_lin, into_enum.elem_linearity().ok());
        let is_ty = value.is_ty();
        assert_eq!(is_ty, into_valid.is_ty());
        assert_eq!(is_ty, into_enum.is_ty());
        assert_eq!(is_ty, ty_lin.is_some());

        // Linearity consistency
        let lin = value.linearity();
        assert_eq!(lin, into_valid.linearity());
        assert_eq!(lin, into_enum.linearity());

        // Constraint consistency
        let locals = value.local_constraints();
        assert_eq!(locals, into_valid.local_constraints());
        assert_eq!(locals, into_enum.local_constraints());

        // Normalization consistency
        let is_normal = value.is_normal();
        let normalized = value.normalized();
        assert_eq!(normalized, into_valid.normalized());
        assert_eq!(normalized, into_enum.normalized());
        match (is_normal, normalized) {
            (true, Some(normalized)) => panic!(
                "Value {:?} is claimed normal, but normalizes to {:?}",
                value, normalized
            ),
            (false, None) => panic!(
                "Value {:?} is claimed non-normal, but does not normalize",
                value
            ),
            (false, Some(normalized)) => assert_ne!(into_valid, *normalized),
            _ => {}
        }
    }
}